// 导入db模块
const db = require('../common/db')

// 定义商品类
class Goods {

    // 新增商品分类名称
    category_add(text) {
        return new Promise((resolve, reject) => {
            // 根据text字段查询是否存在重复的名称
            db.query(`select name from categories where name = '${text}'`)
                .then(
                    row => {
                        // 判断该分类是否存在
                        if (row.length == 0) {
                            // 插入数据的sql语句
                            db.query(`insert into categories(name) values('${text}')`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: "新增商品分类名称",
                                            status: content.changedRows == 0 ? '正常' : '异常'
                                        })
                                    }
                                )
                                .catch(
                                    error => {
                                        reject({
                                            code: -1,
                                            msg: "新增分类失败",
                                            error
                                        })
                                    }
                                )
                        }
                        else {
                            resolve({
                                code: 201,
                                msg: `该分类“${text}”名称已存在`
                            })
                        }
                    }
                )
        })
    }

    // 删除商品分类名称
    category_remove(id) {
        return new Promise((resolve, reject) => {
            // 根据id字段查询是否存在该分类
            db.query(`select id from categories where id = '${id}'`)
                .then(
                    row => {
                        if (row.length == 0) {
                            resolve({
                                code: 404,
                                msg: `这个ID“${id}”分类不存在`
                            })
                        }
                        else {
                            // 执行删除操作
                            db.query(`delete from categories where id = '${id}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: `删除该ID“${id}”分类成功`,
                                            status: content.changedRows === 0 ? '正常' : '异常'
                                        })
                                    }
                                )
                                .catch(
                                    error => {
                                        reject({
                                            code: -1,
                                            msg: `删除该ID“${id}”分类失败`,
                                            error
                                        })
                                    }
                                )
                        }
                    }
                )
        })
    }

    // 获取商品分类列表
    category_list() {
        return new Promise((resolve, reject) => {
            db.query(`select  * from categories`)
                .then(
                    row => {
                        resolve({
                            code: 200,
                            msg: "获取考试分类列表",
                            result: row
                        })
                    },
                    error => {
                        reject({
                            code: -1,
                            msg: "获取考试分类列表失败",
                            error
                        })
                    }
                )
        })
    }


    // 新增商品
    goods_add(name, price, original_price, categoryId, is_promote, option, description, imgUrl) {
        return new Promise((resolve, reject) => {
            // 执行插入的 SQL 语句    
            db.query(`insert into products (price, o_price, category_id, store_name, is_promotional,benefits,description,image_url) 
                VALUES ('${price}', '${original_price}', '${categoryId}', '${name}', '${is_promote}', '${option}','${description}','${imgUrl}')`)
                .then(content => {
                    resolve({
                        code: 200,
                        msg: "新增商品成功",
                        status: content.changedRows == 0 ? '正常' : '异常'
                    });
                })
                .catch(error => {
                    reject({
                        code: -1,
                        msg: "新增商品失败",
                        error
                    });
                });
        });
    }

    // 删除商品
    goods_remove(id) {
        return new Promise((resolve, reject) => {
            // 根据text字段查询是否存在重复的名称
            db.query(`select id from products where id = '${id}'`)
                .then(
                    row => {
                        if (row.length == 0) {
                            resolve({
                                code: 404,
                                msg: `这个ID“${id}”商品不存在`
                            })
                        }
                        else {
                            // 执行删除操作
                            db.query(`delete from products where id = '${id}'`)
                                .then(
                                    content => {
                                        resolve({
                                            code: 200,
                                            msg: `删除该ID“${id}”商品成功`,
                                            status: content.changedRows === 0 ? '正常' : '异常'
                                        })
                                    }
                                )
                                .catch(
                                    error => {
                                        reject({
                                            code: -1,
                                            msg: `删除该ID“${id}”商品失败`,
                                            error
                                        })
                                    }
                                )
                        }
                    }
                )

        })
    }

    // 获取所有商品列表（分页）
    goods_items(page_num, page_size) {
        return new Promise((resolve, reject) => {
            db.query('select count(*) as total from products')
                .then(
                    data => {
                        return data
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "统计失败",
                            err
                        })
                    }
                )
                .then(
                    data => {
                        let num = (parseInt(page_num) - 1) * parseInt(page_size) // 从哪个位置开始获取
                        let size = parseInt(page_size) // 获取多少条记录
                        // 联接查询，获取产品和对应类别的名称
                        db.query(`
                            select p.*, c.name as category_name 
                            from products p
                            left join categories c on p.category_id = c.id
                            limit ${num}, ${size}
                        `)
                            .then(
                                rows => {
                                    resolve({
                                        code: 200,
                                        msg: "获取产品列表成功",
                                        total: data[0] && data[0].total,
                                        result: [...rows]
                                    })
                                },
                                err => {
                                    reject({
                                        code: -1,
                                        msg: "获取产品列表失败",
                                        err
                                    })
                                }
                            )
                    }
                )
        })
    }


}

// 导出考试
module.exports = Goods;
